const getSelector = ele => {
    return typeof ele === "string" ? document.querySelector(ele) : "";
}

// 登录注册载入
const containerShow = () => {
    var show = getSelector(".container")
    show.className += " container-show"
}
window.onload = containerShow;

// 登录注册页切换
((window, document) => {
    // 登录 -> 注册
    let toSignBtn = getSelector(".toSign"),
        toLoginBtn = getSelector(".toLogin")
    loginBox = getSelector(".login-box"),
        signBox = getSelector(".sign-box");
    toSignBtn.onclick = () => {
        loginBox.className += ' animate_login';
        signBox.className += ' animate_sign';
    }
    toLoginBtn.onclick = () => {
        loginBox.classList.remove("animate_login");
        signBox.classList.remove("animate_sign");
    }
})(window, document);

//五个输入框
const signUser = document.querySelector('#sign-user')
const loginUser = document.querySelector('#login-user')
const loginPwd = document.querySelector('#login-password')
const signPwd = document.querySelector('#sign-password')
const verifyCode = document.querySelector('#verify-code')
const signPwd2 = document.querySelector('#sign-password2')
//两个按钮
const signBtn = document.querySelector('.sign-btn')
const loginBtn = document.querySelector('.login-btn')

// 发送验证码
const getVerifyCode = document.querySelector('.getVerifyCode')
getVerifyCode.addEventListener('click', async function () {
    // 验证用户名格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (signUser.value === '') {
        createToast('请输入邮箱地址')
        return
    } else if (!emailRegex.test(signUser.value)) {
        createToast('请输入正确的邮箱地址')
        return
    }
    getVerifyCode.disabled = true;
    let time = 60;
    var timer = setInterval(function () {
        time--;
        getVerifyCode.innerHTML = '重新获取(' + time + 's)';
        getVerifyCode.style.opacity = 0.5
        getVerifyCode.style.cursor = 'not-allowed'
        if (time === 0) {
            clearInterval(timer);
            getVerifyCode.innerHTML = '重新获取';
            getVerifyCode.disable = false
        }
    }, 1000)
    try {
        // 发送验证码请求（端口暂时留空）
        const response = await fetch('http://120.27.154.160:6039/resource/email/code', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username: signUser.value }),
        })
        const data = await response.json()
        if (data.code === 200) {//验证码发送成功
            console.log(data);
        } else {
            createToast('验证码发送失败')
        }
    } catch (error) {
        console.error('发送验证码出错:', error)
    }
})

//隐式提示
const createToast = (message, type = 'error') => {
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;
    document.body.appendChild(toast);
    setTimeout(() => {
        toast.remove();
    }, 3000);
}

signBtn.addEventListener('click', async function () {
    if (signPwd.value.length > 16) {
        createToast('密码长度不能超过16位')
        signPwd.value = ''
        return
    } else if (signPwd.value.length === 0) {
        createToast('请输入密码')
        return
    } else if (signPwd.value.length < 6) {
        createToast('密码长度不能低于6位')
        signPwd.value = ''
        return
    } else if (signPwd.value !== signPwd2.value) {
        createToast('两次密码不一致，请重新输入')
        signPwd.value = ''
        signPwd2.value = ''
        return
    }
    try {
        const response = await fetch('http://120.27.154.160:6039/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: signUser.value,
                password: signPwd.value,
                code: verifyCode.value,
            }),
        })
        if (response.ok) {
            const data = await response.json()
            console.log('注册成功:', data)
            createToast('注册成功', 'success')
            signUser.value = ''
            signPwd.value = ''
            verifyCode.value = ''
            signPwd2.value = ''
        } else {
            createToast('注册失败')
        }
    } catch (error) {
        console.error('注册请求出错:', error)
    }
})

loginBtn.addEventListener('click', async function () {
    if (loginUser.value.length === 0) {
        createToast('请输入邮箱账号')
        return
    }
     if (loginPwd.value.length === 0) {
        createToast('请输入密码')
        return
    }
    // 登录逻辑
    let islogin;
    try {
        const response = await fetch('http://120.27.154.160:6039/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: loginUser.value,
                password: loginPwd.value,
            }),
        })
        const data = await response.json()
        // 修改登录成功逻辑
        if (data.code === 200) {//登录成功
            // 存储token和用户名到本地存储
            if (data.token === '') {
                islogin = 'false'
            } else {
                islogin = 'true'
                localStorage.setItem('token', islogin)
            }
            window.dispatchEvent(new CustomEvent('auth-update'))
            console.log(data)
            console.log('login' + data)
            console.log('islogin' + islogin);
            createToast('登录成功！正在跳转...', "success")
            loginUser.value = ''
            loginPwd.value = ''
            localStorage.setItem('token',data.data.token )
            setTimeout(() => {
                window.location.href = '../chat/index.html'
            }, 3000)
        } else createToast('登录失败,账号或密码错误')
    } catch (error) {
        console.error('登录请求出错:', error)
    }
})

